package com.intellagric.service.product;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.intellagric.common.bean.LayuiDataGridResult;
import com.intellagric.common.bean.ResponseMessage;
import com.intellagric.dao.product.ProductUsedDao;
import com.intellagric.interfaces.product.ProductUsedService;
import com.intellagric.mapper.ProductMapper;
import com.intellagric.mapper.ProductUsedMapper;
import com.intellagric.mapper.SysUserMapper;
import com.intellagric.pojo.Product;
import com.intellagric.pojo.ProductExample;
import com.intellagric.pojo.ProductUsed;
import com.intellagric.pojo.ProductUsedExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class ProductUsedServiceImpl implements ProductUsedService {
    @Autowired
    private ProductUsedMapper mapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductUsedDao dao;

    public ResponseMessage selectProductUsedById(String id) {
        ResponseMessage msg=new ResponseMessage();
        msg.add("usedBean",mapper.selectByPrimaryKey(id));
        return msg;
    }

    public ResponseMessage insertProductUsed(ProductUsed ProductUsed) {
        int remain=this.getUsedCountByProId(ProductUsed.getProduceId())-ProductUsed.getUseNum();
        ProductUsed.setUsedBooked(false);
        ProductUsed.setReturnback(false);
        if(remain<0)
            ProductUsed.setRemainNum(0);
        else
            ProductUsed.setRemainNum(remain);
        int i=mapper.insertSelective(ProductUsed);
        if (i!=0)
            return ResponseMessage.success();
        return ResponseMessage.fail();
    }

    public ResponseMessage deleteProductUsed(String id) {
        int i=mapper.deleteByPrimaryKey(id);
        if (i!=0)
            return ResponseMessage.success();
        return ResponseMessage.fail();
    }

    public ResponseMessage editProductUsed(ProductUsed ProductUsed) {
        ProductUsedExample example=new ProductUsedExample();
        example.createCriteria().andIdEqualTo(ProductUsed.getId());
        int remain=0;
        remain=this.getEditCountByProId(ProductUsed.getProduceId(),ProductUsed.getId())-ProductUsed.getUseNum();
        if(remain<0)
            ProductUsed.setRemainNum(0);
        else
            ProductUsed.setRemainNum(remain);
        int i =mapper.updateByExampleSelective(ProductUsed,example);
        if (i!=0)
            return ResponseMessage.success();
        return ResponseMessage.fail();
    }


    public LayuiDataGridResult getList(int page, int limit) {
        PageHelper.startPage(page,limit);
        ProductUsedExample example=new ProductUsedExample();
        example.createCriteria().andProduceIdIsNotNull().andUsedBookedEqualTo(false).andReturnbackEqualTo(false);
        example.or().andProduceIdIsNotNull().andUsedBookedEqualTo(true).andReturnbackEqualTo(true);
        List<ProductUsed> list=mapper.selectByExample(example);
        PageInfo info=new PageInfo(list);
        return LayuiDataGridResult.success().add(list,info.getTotal());
    }
    public LayuiDataGridResult getListByCategoryId(int page,int limit,String categoryId){
        ProductExample example=new ProductExample();
        example.createCriteria().andCategoryIdEqualTo(categoryId);
        List<Product> list=productMapper.selectByExample(example);
        List<ProductUsed> results=new ArrayList<ProductUsed>();
        for (Product pro:list){
            ProductUsedExample usedExample=new ProductUsedExample();
            usedExample.createCriteria().andProduceIdEqualTo(pro.getProduceId()).andUsedBookedEqualTo(false).andReturnbackEqualTo(false);
            usedExample.or().andProduceIdEqualTo(pro.getProduceId()).andUsedBookedEqualTo(true).andReturnbackEqualTo(true);
            results.addAll(mapper.selectByExample(usedExample));
        }

        int toIndex=(page-1)*limit+limit;
        if(toIndex>results.size()){
            toIndex=results.size();
        }
        return LayuiDataGridResult.success().add(results.subList((page-1)*limit,toIndex),results.size());
    }

    public LayuiDataGridResult batchDeleteProductUsed(String[] ids) {
        int i=dao.batchDeleteByPrimaryKey(ids);
        if (i!=0)
            return LayuiDataGridResult.success();
        return LayuiDataGridResult.fail();
    }

    /**
     * 根据商品名查询使用情况
     * @param page
     * @param limit
     * @param keyword
     * @return
     */
    public LayuiDataGridResult getProductUsedByKeyword(int page, int limit, String keyword) {
        ProductExample productExample=new ProductExample();
        productExample.createCriteria().andProduceNameLike("%"+keyword+"%");
        List<Product> productList=productMapper.selectByExample(productExample);
        List<ProductUsed> results=new ArrayList<ProductUsed>();
        for (Product product:productList){
            ProductUsedExample example=new ProductUsedExample();
            example.createCriteria().andProduceIdEqualTo(product.getProduceId()).andReturnbackEqualTo(false).andUsedBookedEqualTo(false);
            example.or().andProduceIdEqualTo(product.getProduceId()).andReturnbackEqualTo(true).andUsedBookedEqualTo(true);
            results.addAll(mapper.selectByExample(example));
        }
        int toIndex=(page-1)*limit+limit;
        if(toIndex>results.size()){
            toIndex=results.size();
        }
        return LayuiDataGridResult.success().add(results.subList((page-1)*limit,toIndex),results.size());
    }
    /**
     * 根据商品名查询预定情况
     * @param page
     * @param limit
     * @param keyword
     * @return
     */
    public LayuiDataGridResult getProductBookedByKeyword(int page, int limit, String keyword) {
        ProductExample productExample=new ProductExample();
        productExample.createCriteria().andProduceNameLike("%"+keyword+"%");
        List<Product> productList=productMapper.selectByExample(productExample);
        List<ProductUsed> results=new ArrayList<ProductUsed>();
        for (Product product:productList){
            ProductUsedExample example=new ProductUsedExample();
            example.or().andProduceIdEqualTo(product.getProduceId()).andReturnbackEqualTo(false).andUsedBookedEqualTo(true);
            results.addAll(mapper.selectByExample(example));
        }
        int toIndex=(page-1)*limit+limit;
        if(toIndex>results.size()){
            toIndex=results.size();
        }
        return LayuiDataGridResult.success().add(results.subList((page-1)*limit,toIndex),results.size());
    }

    public int getUsedCountByProId(String productId) {
        Product product=productMapper.selectByPrimaryKey(productId);
        Integer integer=product.getBuyNum();
        if (integer==null)
            return 0;
        ProductUsedExample example=new ProductUsedExample();
        example.createCriteria().andProduceIdEqualTo(productId).andUsedBookedEqualTo(false).andReturnbackEqualTo(false);
        if(mapper.selectByExample(example).size()==0){
            return integer;
        }
        int result=product.getBuyNum()-dao.getUsed(productId);
        if (result<0)
            return 0;
        return result;
    }

    /**
     * 减掉其它使用量再加上本身
     * @param productId
     * @param usedId
     * @return
     */
    public int getEditCountByProId(String productId,String usedId) {
        Product product=productMapper.selectByPrimaryKey(productId);
        Integer integer=product.getBuyNum();
        if (integer==null)
            return 0;
        ProductUsedExample example=new ProductUsedExample();
        example.createCriteria().andProduceIdEqualTo(productId).andUsedBookedEqualTo(false);
        if(mapper.selectByExample(example).size()==0){
            return integer;
        }
        int result=product.getBuyNum()-dao.getUsed(productId)+mapper.selectByPrimaryKey(usedId).getUseNum();
        if (result<0)
            return 0;
        return result;
    }
    /**
     *  预约列表
     * @param page
     * @param limit
     * @return
     */
    @Override
    public LayuiDataGridResult getBookedList(int page, int limit) {
        PageHelper.startPage(page,limit);
        ProductUsedExample example=new ProductUsedExample();
        example.createCriteria().andUsedBookedEqualTo(true).andReturnbackEqualTo(false);//标记为借用
        List<ProductUsed> list=mapper.selectByExample(example);
//        List<ProductUsed> list=dao.getList();
        PageInfo info=new PageInfo(list);
        return LayuiDataGridResult.success().add(list,info.getTotal());
    }

    /**
     * 根据分类获取预约列表
     * @param page
     * @param limit
     * @param categoryId
     * @return
     */
    @Override
    public LayuiDataGridResult getBookedListByCategoryId(int page, int limit, String categoryId) {
        ProductExample example=new ProductExample();
        example.createCriteria().andCategoryIdEqualTo(categoryId);
        List<Product> list=productMapper.selectByExample(example);
        List<ProductUsed> results=new ArrayList<ProductUsed>();
        for (Product pro:list){
            ProductUsedExample usedExample=new ProductUsedExample();
            usedExample.createCriteria().andProduceIdEqualTo(pro.getProduceId()).andUsedBookedEqualTo(true).andReturnbackEqualTo(false);

            results.addAll(mapper.selectByExample(usedExample));
        }

        int toIndex=(page-1)*limit+limit;
        if(toIndex>results.size()){
            toIndex=results.size();
        }
        return LayuiDataGridResult.success().add(results.subList((page-1)*limit,toIndex),results.size());
    }

    /**
     * 根据id查询此设备剩余可预定的数量
     * @return
     */
    private int getBookedRemainCountByProIdAndTime(String productId, Date useDate){
        Product product=productMapper.selectByPrimaryKey(productId);
        Integer integer=product.getBuyNum();

        ProductUsedExample example=new ProductUsedExample();
        example.createCriteria().andProduceIdEqualTo(productId).andUsedBookedEqualTo(false);
        int remain=integer-mapper.selectByExample(example).size();//购买量减使用量
        if(remain<=0){
            return 0;
        }
        ProductUsedExample example1=new ProductUsedExample();
        example1.createCriteria().andUsedBookedEqualTo(true).andProduceIdEqualTo(productId).andReturnbackEqualTo(false);
        List<ProductUsed> bookList=mapper.selectByExample(example1);
        int bookNum=0;
        for (ProductUsed used: bookList){
            if(useDate.after(used.getUseDate())&&useDate.before(used.getReturnDate())){
                bookNum+=used.getUseNum();
            }
        }
        return remain-bookNum<=0?0:remain-bookNum;

    }
    /**
     * 添加预约记录
     * @param ProductUsed
     * @return
     */
    public ResponseMessage insertProductBooked(ProductUsed ProductUsed) {
        int remainBookable=getBookedRemainCountByProIdAndTime(ProductUsed.getProduceId(),ProductUsed.getUseDate());
        if (remainBookable==0){
            ResponseMessage resp=new ResponseMessage();
            resp.setMessage("当前可预订的设备数量不足");
            resp.setCode(100);
            return resp;
        }else if(remainBookable<ProductUsed.getUseNum()){
            ResponseMessage resp=new ResponseMessage();
            resp.setMessage("当前可预订的设备数量不足");
            resp.setCode(100);
            return resp;
        }
        ProductUsed.setReturnback(false);
        ProductUsed.setUsedBooked(true);
        ProductUsed.setRemainNum(remainBookable-ProductUsed.getUseNum());
        if (mapper.insertSelective(ProductUsed)!=0){
            return ResponseMessage.success();
        }
        return ResponseMessage.fail();
    }

    @Override
    public LayuiDataGridResult bookReturn(String productUsedId) {
        ProductUsedExample example=new ProductUsedExample();
        example.createCriteria().andIdEqualTo(productUsedId);
        ProductUsed used=new ProductUsed();
        used.setReturnback(true);
        if(mapper.updateByExampleSelective(used,example)!=0){
         return LayuiDataGridResult.success();
        }
        return LayuiDataGridResult.fail();
    }
    @Override
    public LayuiDataGridResult batchBookReturn(String[] productUsedIds) {
        int i=0;
        for (String productUsedId: productUsedIds) {
            ProductUsedExample example = new ProductUsedExample();
            example.createCriteria().andIdEqualTo(productUsedId);
            ProductUsed used = new ProductUsed();
            used.setReturnback(true);
            i+=mapper.updateByExampleSelective(used,example);
        }
        if(i==productUsedIds.length){
            return LayuiDataGridResult.success();
        }
        return LayuiDataGridResult.fail();
    }

    @Override
    public String[] getRecentDate() {
        Calendar calendar=Calendar.getInstance();
        //calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH));
        String[] strs=new String[7];
        for (int i =6;i>=0;i--) {
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            strs[i]=calendar.get(calendar.MONTH)+1+"月"+calendar.get(Calendar.DAY_OF_MONTH)+"日";
        }

        return strs;
    }

    @Override
    public long[] getRecentData() throws ParseException {
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");

        Calendar calendar=Calendar.getInstance();
        long[] ints=new long[7];
        for (int i =6;i>=0;i--) {
            String tomorrow=calendar.get(Calendar.YEAR)+"-"+(calendar.get(Calendar.MONTH)+1)+"-"+calendar.get(Calendar.DAY_OF_MONTH);
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            String today=calendar.get(Calendar.YEAR)+"-"+(calendar.get(Calendar.MONTH)+1)+"-"+calendar.get(Calendar.DAY_OF_MONTH);
            Date date=format.parse(today);
            ProductUsedExample example=new ProductUsedExample();
            example.createCriteria().andUseDateBetween(date,format.parse(tomorrow));
            ints[i]=mapper.countByExample(example);
        }


        return ints;
    }
}
